#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/30  9:35
# @Author: 余浪人
# @email: yulangren520@gmail.com
import random
from datetime import datetime
from apps.lib.cache_sys import sys_cache, cache
from apps.lib.public import get_date, redis_, visiting_user, check_obj
from apps.models.system_model import TL_Blogroll_Model, TL_Notice_Model, TL_Ad_Model
from apps.webapi import webApi_bp
from flask import jsonify, request, make_response
from apps.models.content_model import TL_Content_Model, TL_Column_model, TL_Comment_Model, db
from apps.webapi.webpublic.public import page_auto, content, apiErrors, notNull, img, click_up, authority, conmmentAuthority, ipAdd, ipAuthority, nav_list


# 首页最近更新
@webApi_bp.route('/IndexList', endpoint='IndexList', methods=['GET'])
@ipAuthority
@authority
@cache.cached(timeout=24*(60*60),key_prefix='IndexList')
def indexList():
    nowList = TL_Content_Model.query.order_by(TL_Content_Model.is_index_stick.desc()).order_by(
        TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1,
                                           TL_Content_Model.update_time < datetime.now())
    data, page = page_auto(nowList, 20, 4)  # 返回26条,4页
    data = {
        "status": 0,
        'msg': 'successful',
        'presentPage': page.page,
        "dataList": content(data, '%Y-%m-%d')
    }
    return jsonify(data)


# 导航分类
@webApi_bp.route('/nav', endpoint='nav', methods=['GET'])
@ipAuthority
@ipAdd
@authority
@visiting_user
@cache.cached(timeout=24*(60*60),key_prefix='api_nav')
def nav():
    column = TL_Column_model.query.order_by(TL_Column_model.column_order.desc()).order_by(TL_Column_model.id.asc()).filter(
        TL_Column_model.status == 1).all()
    data = {
        "status": 0,
        'msg': 'successful',
        'amount': len(column),
        'dataList': nav_list(column)
    }
    return jsonify(data)


# 随机推荐
@webApi_bp.route('/randomRecommend', endpoint='randomRecommend', methods=['GET'])
@ipAuthority
@authority
def random_recommend():
    con = TL_Content_Model.query.filter(TL_Content_Model.status == 1, TL_Content_Model.update_time < datetime.now()).count()
    random_document = random.sample(TL_Content_Model.query.filter(TL_Content_Model.status == 1, TL_Content_Model.update_time < datetime.now()).all(),20 if con >= 20 else con)  # 随机推荐 20条
    data = {
        "status": 0,
        'msg': 'successful',
        'dataList': content(random_document, '%Y-%m-%d')
    }
    return jsonify(data)


# 友情链接
@webApi_bp.route('/blogroll', endpoint='blogroll', methods=['GET'])
@ipAuthority
@authority
@cache.cached(timeout=24*(60*60),key_prefix='api_blogroll')
def blogroll():
    blogroll = TL_Blogroll_Model.query.order_by(TL_Blogroll_Model.link_sort.desc()).filter(TL_Blogroll_Model.status == 1,
                                                                                           TL_Blogroll_Model.link_end_date >= datetime.now()).all()
    data = {
        "status": 0,
        'msg': 'successful',
        'dataList': [
            {
                "link_name": data.link_name,
                "link_url": data.link_url,
                "link_color": data.link_color,
            }
            for data in blogroll
        ]
    }
    return jsonify(data)


# 点击排名接口
@webApi_bp.route('/clickOrder', endpoint='clickOrder', methods=['GET'])
@ipAuthority
@authority
@cache.cached(timeout=24*(60*60),key_prefix='api_clickOrder')
def click_order():
    cont = TL_Content_Model.query.order_by(TL_Content_Model.clicks.desc()).filter(
        TL_Content_Model.update_time < datetime.now()).all()[0:50]  # 最多返回50个
    data = {
        "status": 0,
        'msg': 'successful',
        'dataList': content(cont, '%Y-%m-%d')
    }
    return jsonify(data)


# 分类更新
@webApi_bp.route('/columnUpdate', endpoint='columnUpdate', methods=['POST'])
@ipAuthority
@authority
@cache.cached(timeout=24*(60*60),key_prefix='api_columnUpdate')
def columnUpdate():
    column = TL_Column_model.query.order_by(TL_Column_model.column_order.asc()).filter().all()
    data = {
        "status": 0,
        'msg': 'successful',
        'colList': [{
            'column_name': col.column_name,
            'column_link': col.column_link,
            'column_ID': col.uuid,
            'dataList': content(col.content_model[:50], '%Y-%m-%d')  # 返回50条数据
        }
            for col in column
        ]
    }
    return jsonify(data)


# 分类信息(列表页)
@webApi_bp.route('/columnList', endpoint='columnList', methods=['POST'])
@ipAuthority
@authority
@visiting_user
@cache.cached(timeout=24*(60*60),key_prefix='api_columnList')
def columnList():
    pid = request.json.get('PID') if request.is_json else request.form.get('PID')  # 分类uuid
    column = TL_Column_model.query.filter_by(uuid=pid).first()
    if apiErrors(column): return apiErrors(column)
    contList = TL_Content_Model.query.order_by(TL_Content_Model.is_list_stick.desc()).order_by(
        TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1, TL_Content_Model.superior == column.id)
    dataList, page = page_auto(contList, 10, )  # 一页10条
    data = {
        "status": 0,
        'msg': 'successful',
        'PID': column.uuid,
        'pageList': {
            "total": page.total,
            "prev": page.has_prev,
            "prevPage": notNull(page.prev_num),
            "next": page.has_next,
            'nextPage': notNull(page.next_num),
            'currentPage': page.page,
            'pages': page.pages,
            'iter_pages': [pg for pg in page.iter_pages(2, 2, 2, 2) if pg]
        },
        'dataList': content(dataList, '%Y-%m-%d')
    }
    return jsonify(data)


# 详情数据
@webApi_bp.route('/detail', endpoint='detail', methods=['POST'])
@ipAuthority
@authority
@visiting_user
@click_up
@cache.cached(timeout=30*(24*(60*60)),key_prefix='api_detail')
def detail():
    pid = request.json.get('pid') if request.is_json else request.form.get('pid')
    con = TL_Content_Model.query.filter_by(uuid=pid, status=1).first()
    if apiErrors(con): return apiErrors(con)
    data_s = con.pro.content_model
    num = 2 if len(data_s) >= 2 else len(data_s)
    page = random.sample(data_s, num)  # 实现上下页
    if len(page) == 2:
        next_page = {
            "title": page[0].title,
            "ID": page[0].uuid,
            'imgUrl': img(page[0].thumb_img, page[0].content),
        }
        last_page = {
            "title": page[1].title,
            "ID": page[1].uuid,
            'imgUrl': img(page[1].thumb_img, page[1].content),
        }
    elif len(page) == 1:
        next_page = {
            "title": page[0].title,
            "ID": page[0].uuid,
            'imgUrl': img(page[0].thumb_img, page[0].content),
        }
        last_page = {"title": '', "ID": '', 'imgUrl': '', }
    else:
        next_page = {"title": '', "ID": '', 'imgUrl': ''}
        last_page = {"title": '', "ID": '', 'imgUrl': ''}
    data = {
        "status": 0,
        "msg": 'successful',
        "similar": content(con.pro.content_model[:20][::-1], '%Y-%m-%d'),
        "data": {
            "title": con.title,
            'ID': con.uuid,
            'update_time': con.update_time.strftime('%Y-%m-%d'),
            'title_color': con.title_color,
            'imgUrl': img(con.thumb_img, con.content),
            'PID': con.pro.column_name,
            'author': con.author,
            'clicks': con.clicks,
            'contributor': con.contributor,
            'description': con.description,
            'content': con.content,
            'permissions': con.permissions,
            'download': con.download,
            'keyword': con.keyword,
            'is_focus': con.is_focus,
            'is_roll': con.is_roll,
            'is_roll_text': con.is_roll_text,
            'is_index_stick': con.is_index_stick,
            'is_list_stick': con.is_list_stick,
            'pay': con.reward,
        },
        "commentList": [{
            "comment_txt": da.comment_txt,
            "user_qq": da.user_qq,
            "user_name": da.user_name,
            "create_time": da.create_time.strftime('%Y-%m-%d'),
        } for da in (con.comment_model[:100])[::-1] if da.status],
        "next_page": next_page,
        "last_page": last_page,
    }
    return jsonify(data)


# 公告
@webApi_bp.route('/notice', endpoint='notice', methods=['GET'])
@ipAuthority
@authority
@cache.cached(timeout=48*(60*60),key_prefix='api_notice')
def notice():
    noticeList = TL_Notice_Model.query.order_by(TL_Notice_Model.id.desc()).filter(TL_Notice_Model.status == 1).all()
    data = {
        "status": 0,
        "msg": 'successful',
        'data': [
            {
                'title': new.notice_title,
                'promulgator': new.notice_promulgator,
                'content': new.notice_content,
                'date': new.update_time.strftime('%m-%d'),
                'id': new.uuid,
            }
            for new in noticeList
        ]
    }
    return jsonify(data)


# 轮播图 限制50
@webApi_bp.route('/lantern', endpoint='lantern', methods=['GET'])
@ipAuthority
@authority
@cache.cached(timeout=24*(60*60),key_prefix='api_lantern')
def lantern():
    conList = TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1,
                                                                                 TL_Content_Model.is_roll == 1,
                                                                                 TL_Content_Model.update_time < datetime.now()).all()
    data = {
        "status": 0,
        'msg': 'successful',
        "dataList": content(conList[:50])
    }
    return jsonify(data)


# 系统信息
@webApi_bp.route('/webConf', methods=['GET'])
@ipAuthority
@authority
@cache.cached(timeout=48*(60*60),key_prefix='api_webConf')
def web():
    sys = sys_cache()
    data = {
        "status": 0,
        'msg': 'successful',
        "data": {
            'web_name': sys.web_name,
            'web_subtitle': sys.web_subtitle,
            "web_key": sys.web_key,
            "web_description": sys.web_description,
            "web_domain": sys.web_domain,
            'web_logo': sys.web_logo,
            "web_ico": sys.web_ico,
            "web_stat": sys.web_stat,
            "web_close_tips": sys.web_close_tips,
            "web_company": sys.web_company,
            "web_contact_adders": sys.web_contact_adders,
            "web_contact_tel": sys.web_contact_tel,
            "web_info_copyright": sys.web_info_copyright,
            "web_record": sys.web_record,
            "web_contact_qq": sys.web_contact_qq,
            "web_contact_email": sys.web_contact_email
        }
    }
    return jsonify(data)


# 广告信息获取
@webApi_bp.route('/ad', endpoint='ad', methods=['GET'])
@cache.cached(timeout=30*(24*(60*60)),key_prefix='api_ad')
def ad_get():
    uid = request.args.get('pid')
    ad = TL_Ad_Model.query.filter_by(uuid=uid, status=1).first()
    if apiErrors(ad): return apiErrors(ad)
    code = ad.ad_code if ad.status else ''
    data = {
        "status": 0,
        "msg": 'successful',
        "data": {
            'adCode': code,
            'ad_name': ad.ad_name,
            'ad_end_date': ad.ad_end_date.strftime('%Y-%m-%d'),
        }
    }
    return jsonify(data)


# js广告信息获取
@webApi_bp.route('/ad_js_<string:uid>', endpoint='ad_js', methods=['GET'])
@ipAuthority
@cache.cached(timeout=48*(60*60),key_prefix='api_ad_js')
def ad_js_get(uid):
    ad = TL_Ad_Model.query.filter_by(uuid=uid, status=1).first()
    if check_obj(ad): return check_obj(ad)
    content = f"""document.write("{ad.ad_code}");"""
    response = make_response(content)
    response.headers['Content-Type'] = 'application/javascript'
    return response


# 推荐信息50
@webApi_bp.route('/recommend', endpoint='recommend', methods=['GET'])
@ipAuthority
@authority
@cache.cached(key_prefix='api_recommend')
def recommend():
    conList = TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1,TL_Content_Model.is_recommend == 1,TL_Content_Model.update_time < datetime.now()).all()
    data = {
        "status": 0,
        'msg': 'successful',
        "dataList": content(conList[:50], strftime='%Y-%m-%d')
    }
    return jsonify(data)


# 公告详情获取
@webApi_bp.route('/noticeDetail', endpoint='noticeDetail', methods=['GET'])
@ipAuthority
@visiting_user
@cache.cached(timeout=30*(24*(60*60)),key_prefix='api_noticeDetail')
def noticeDetail():
    uid = request.args.get('pid') if request.args.get('pid') else request.form.get('pid')
    notice = TL_Notice_Model.query.filter_by(uuid=uid).first()
    if apiErrors(notice): return apiErrors(notice)
    data = {
        "status": 0,
        "msg": 'successful',
        "data":
            {
                'title': notice.notice_title,
                'promulgator': notice.notice_promulgator,
                'content': notice.notice_content,
                'date': notice.update_time.strftime('%m-%d'),
                'id': notice.uuid,
            }
    }
    return jsonify(data)


# 评论获取
@webApi_bp.route('/comment', endpoint='comment', methods=['POST'])
@ipAuthority
@authority
@conmmentAuthority
def comment():
    pid = request.json.get('pid') if request.is_json else request.form.get('pid')
    con = TL_Content_Model.query.filter_by(uuid=pid, status=1).first()
    if apiErrors(con): return apiErrors(con)
    data = {
        "status": 0,
        "msg": 'successful',
        "dataList": [
            {
                'comment_txt': da.comment_txt,
                'user_qq': da.user_qq,
                'user_name': da.user_name,
                "create_time": da.update_time,
            }
            for da in (con.comment_model[:100])[::-1] if da.status]
    }
    return jsonify(data)


# 评论发布
@webApi_bp.route('/comment_post', endpoint='comment_post', methods=['POST'])
@ipAuthority
@authority
@conmmentAuthority
def comment_post():
    pid = request.json.get('content_uuid') if request.is_json else request.form.get('content_uuid')
    con = TL_Content_Model.query.filter_by(uuid=pid, status=1).first()
    if apiErrors(con): return apiErrors(con)
    comment_txt = request.json.get('comment_txt') if request.is_json else request.form.get('comment_txt')
    if comment_txt and not len(comment_txt) >= 5: return jsonify({"status": 406, "msg": "内容长度不足!"})
    user_qq = request.json.get('user_qq') if request.is_json else request.form.get('user_qq')
    user_name = request.json.get('user_name') if request.is_json else request.form.get('user_name')
    obj = TL_Comment_Model()
    try:
        obj.set_attrs({"comment_txt": comment_txt, "content_uuid": pid, "user_qq": user_qq, "user_name": user_name})
        db.session.add(obj)
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({"status": 1, "msg": "评论发布失败!"})
    redis_().delete(pid)  # 更新缓存
    return jsonify({
        "status": 0,
        "msg": "successful!",
        "commentData": {
            "comment_txt": comment_txt,
            "user_qq": user_qq,
            "user_name": user_name,
            "create_time": get_date().strftime('%Y-%m-%d'),
        }
    })
